<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/13
 * Time: 16:10
 */

namespace app\api\controller;

use app\common\lib\Aes;
use app\common\lib\exception\ApiException;
use app\common\lib\Time;
use think\Cache;
use think\Controller;
use app\common\lib\IAuth;

class Common extends Controller
{

    /**
     * page
     * @var string
     */
    public $page = '';
    /**
     * 每页显示多少条
     * @var string
     */
    public $size = '';
    /**
     * 查询条件的起始值
     * @var int
     */
    public $from = 0;

    /**
     * headers 信息
     * @var string
     */
    public $headers = '';

    /**
     * 初始化的方法
     */
    public function _initialize()
    {
        $this->checkRequestAuth();
        //$this->testAes();
    }

    /**
     *  检查每次 app 请求的数据是否合法
     */
    public function checkRequestAuth(){
        //首先需要获取 headers
        $headers = request()->header();
        // sign 加密需要 客户端工程师 ， 解密： 服务端工程师
        //1 headers body 仿照 sign

        if(empty($headers['sign'])){
            throw new ApiException('sign不存在', 400);
        }
        if(!in_array($headers['app-type'], config('app.apptypes'))){
            throw new ApiException('app-type不合法', 400);
        }

        // 需要 sign
        if (!IAuth::checkSignPass($headers)) {
            throw new ApiException('授权码sign失败', 401);
        }
        // 1、 文件  2、 mysql 3、 redis
        Cache::set($headers['sign'], 1, config('app.app_sign_cache_time'));
        $this->headers = $headers;

    }

    public function testAes(){
        $data = [
            'did' => '123456dg',
            'version' => 18,
            'time' => Time::get13TimeStamp(),
        ];

        //halt($data);

       $string = IAuth::setSign($data);

       echo $string.PHP_EOL;

       $vd = (new Aes())->decrypt($string);

        echo $vd.PHP_EOL;
        exit;
    }

    /**
     * 获取分页 page size 内容
     * @param $data
     */
    public function getPageAndSize ( $data) {
        $this->page = !empty($data['page']) ? $data['page'] : 1;
        $this->size = !empty($data['size']) ? $data['size'] : config('paginate.list_rows');
        $this->from = ($this->page - 1) * $this->size;
    }

    /**
     * 栏目处理函数
     * @param array $news
     * @return array|mixed
     */
    protected function getDealNews($news = []){
        if (empty($news)) {
            return [];
        }
        $cats = config('cat.lists');
        foreach ($news as $key => $value) {
            $news[$key]['catname'] = $cats[$value['catid']] ? $cats[$value['catid']] : '-';
        }
        return $news;
    }

}